// pages/ctrldevices/ctrldevices.js
var util = require('../../utils/util.js');
var api = require('../../config/api.js')
var onenetstudio = require('../../utils/onenetstudio.js');
const aliSdk = require("../../utils/ali_iot_util/aliIot-sdk.js");
var base64 = require('../../utils/base64.js');

// const device_name = "mycarep1";


Page({

  /**
   * 页面的初始数据
   */
  data: {
    onenet_deviceid:0,
    onenet_pid:311038,
    device_name:'',           //onenet studio 平台设备名
    device_nickname:'',       //设别名称
    led_onoff1:0,         //led1 开关
    led_onoff2:0,         //led1 开关
    led_onoff3:0,         //led1 开关
    relay_ctrl1:0,          //继电器控制
    tgt_temperature:0,        //目标温度
    read_gear:0,        //读速度
    connectionState:0,           //设备网络连接状态
    lingmin:0,             //灵敏度调整
    testa:0,             //备用a
    testb:0,             //备用b
    
    RSSI:0,
    lng:0,        //经度
    lat:0,        //纬度
    power:0,        //电压
    iostate:0,        //读设备 IO口状态
    dvc_temperature:0,        //设备温度
    adc:0,        //读  设备ADC值
    comdata:0,        //读十六进制数组
    //读image 状态
    deviceId: "580667032",
    createTime: 1594885971,
    status: "enabled",
    statusReason: "created",
    statusUpdateTime: 0,
    lastActivityTime: 0,
    //读image  reported  状态
    rpt_baudrate: 4400,
    rpt_endtime: 1687221654,
    rpt_conf2: 8,
    rpt_iostate: 11,
    rpt_conf1: 6,
    rpt_version: "v1.1",
    rpt_temp1: 25.8,
    rpt_iccid: "89860448181940053787",
    rpt_imei: 8,
    rpt_power: 3996,
    rpt_lat: 45.820952,
    //读image  desired  状态
    desired_baudrate: 9600,
    desired_relaynum: 3,
    desired_endtime: 1687221650,
    desired_conf2: 8,
    desired_conf1: 6,
    //读image  delta  状态

    //数据更新时间
    updata_min:0,
    updata_sec:0,

    //定时器 ID
    setInter:0,






  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    const device_name = options.id;
    // const onenet_deviceid = options.onenet_deviceid;

    console.log('device_name',device_name);
    console.log('options',options);

    that.setData({
      device_name: device_name
    })

    const params4 = {
      query:{
          "project_id": api.project_id,
          "product_id": api.product_id,
          "device_name": device_name,
      },
      "body": {
          "params": {}
      }
    };


    // 读取设备属性状态
        const config1 = {
          Action: "GetDeviceStatus",
          ProductKey: api.productKey,
          DeviceName: api.deviceName
        };
        // RRPC 向指定设备发送请求消息，并同步返回响应
        // const config1 = {
        //   Action: "RRpc",
        //   ProductKey: api.productKey,
        //   DeviceName: api.deviceName,
        //   timeout: 6666,
        //   requestBase64Byte: base64.encode(JSON.stringify(data1)),
        // };
        aliSdk.request(config1, {
          method: "POST"
        },
        (res) => {
          console.log("success")
          console.log(res) //查看返回response数据
          if (res.data.Code) {
            console.log(res.data.ErrorMessage)
            wx.showToast({
              title: '设备连接失败',
              icon: 'none',
              duration: 1000,
              complete: () => {}
            })
            // that.setPropertyData(null)
            console.log("1111nihao ")
          } else {
            console.log("2222nihao ",res);
            if (res.data.Success == true) {
              console.log(' 设备状态', res.data.Data.Status);
              if(res.data.Data.Status == "ONLINE"){
                that.setData({
                  connectionState: true
                })
              }else if(res.data.status == "OFFLINE"){
                that.setData({
                  connectionState: false
                })
              }
            } else {
              console.log('device status errer', res)
            }
            
          }
        },
        (res) => {
          console.log("fail")
          wx.showToast({
            title: '网络连接失败',
            icon: 'none',
            duration: 1000,
            complete: () => {}
          })
          // this.setPropertyData(null)
        },
        (res) => {
          console.log("complete")
          
        })



    // //data.status:int 类型 设备状态 1-未激活 2-在线 3-离线
    // onenetstudio.oneNetSDK.APPQueryDeviceStatus(params4).then(function (res) {
    //   console.log('onenetcimg')
    //   if (res.success == true) {
    //     console.log(' 设备状态', res);
    //     if(res.data.status == 2){
    //       that.setData({
    //         connectionState: true
    //       })
    //     }else if(res.data.status == 3){
    //       that.setData({
    //         connectionState: false
    //       })
    //     }
    //   } else {
    //     console.log('device status errer', res)
    //   }

    // });

    //读 镜像image 信息
    // util.onenetcimg(onenet_deviceid, onenet_pid).then(function (res) {
    //   console.log('onenetcimg')
    //   if (res.errMsg == "request:ok") {
    //     console.log('IMAGE222 ', res);
    //     if(res.data.data.connectionState == "online"){
    //       that.setData({
    //         connectionState: true
    //       })
    //     }else if(res.data.data.connectionState == "offline"){
    //       that.setData({
    //         connectionState: false
    //       })
    //     }
    //   } else {
    //     console.log('IMAGE333', res)
    //   }
    // });
    //读 数据流信息
    // util.onenetcdate(onenet_deviceid, onenet_pid).then(function (res) {
    //   console.log('onenetcdate')
    //   if (res.data.errno === 0) {
    //     console.log('data ', res);

    //   } else {
    //     console.log('data333', res)
    //   }
    // });
    //wx to onenet 20201004
    // const params2 = {
    //   query:{},
    //   "body": {
    //     "project_id": api.project_id,
    //     "product_id": api.product_id,
    //     "device_name": device_name,
    //     "params":{
    //       "RSSI": 55,
    //       "comdata": "8986044818194005378716"

    //     }
    //   }
    // }
    // onenetstudio.oneNetSDK.APPSetDeviceProperty(params2).then(function (res) {

    //     console.log('123456APPSetDeviceProperty', res);
  
    // });


    const params3 = {
      query:{},
      "body": {
        "project_id": api.project_id,
        "product_id": api.product_id,
        "device_name": device_name,
        "params":{
          "useron": "01"
        }
      }
    }
    onenetstudio.oneNetSDK.APPSetDeviceProperty(params3).then(function (res) {
      // that.delay_refrash(that);
      console.log('useron', res);
      if(res.success == true){
        console.log('delay 1.2秒');
        setTimeout(function() {
          that.delay_refrash(that);
        }, 1300);
      }
    });


    // util.onenetctrl(onenet_deviceid, "01", onenet_pid,'useron').then(function (res) {
    //   console.log('onload', res);
    //   // console.log('onload111', res.devicesupdata.ctrldata_res.useron.dp.temp[0].v);
    //   // console.log('onload222', res.devicesupdata.ctrldata_res.gear);
    //   if (res.errno === 0) {
    //     that.setData({
    //       read_gear:res.devicesupdata.ctrldata_res.gear,        //读速度
    //       lingmin:res.devicesupdata.ctrldata_res.lingmin,             //灵敏度调整
    //       testa:res.devicesupdata.ctrldata_res.testa,             //备用a
    //       testb:res.devicesupdata.ctrldata_res.testb,             //备用b
          
    //       led_onoff1:parseInt(res.devicesupdata.ctrldata_res.useron.dp.iostate[0].v[7]),         //开关机
    //       relay_ctrl1:parseInt(res.devicesupdata.ctrldata_res.useron.dp.iostate[0].v[6]),          //继电器控制
    //       lng:res.devicesupdata.ctrldata_res.useron.dp.lng[0].v,        //经度
    //       lat:res.devicesupdata.ctrldata_res.useron.dp.lat[0].v,        //纬度
    //       power:(res.devicesupdata.ctrldata_res.useron.dp.power[0].v/1000),        //电压
    //       iostate:res.devicesupdata.ctrldata_res.useron.dp.iostate[0].v,        //读设备 IO口状态
    //       dvc_temperature:res.devicesupdata.ctrldata_res.useron.dp.temp[0].v,        //设备温度
    //       tgt_temperature:(res.devicesupdata.ctrldata_res.useron.dp.adc[0].v /100),        //读  设备ADC值
    //       comdata:res.devicesupdata.ctrldata_res.useron.dp.comdata[0].v,        //读十六进制数组
    //     })
    //   } else {

    //   }
    // });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that =this;
    //清除计时器 即清除setInter
    clearInterval(that.data.setInter)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
//led1灯开关  控制
  onoff(e) {
    // console.log('success!!',e);

    let onoffbuf = "";
    if(e.detail.value == true){
      onoffbuf = "0011";
    }else{
      onoffbuf = "0010";
    }
    //ONENET 平台链接方式
    // const params4 = {
    //   query:{},
    //   "body": {
    //     "project_id": api.project_id,
    //     "product_id": api.product_id,
    //     "device_name": this.data.device_name,
    //     "params":{
    //       "ctrlpin": onoffbuf
    //     }
    //   }
    // }
    // onenetstudio.oneNetSDK.APPSetDeviceProperty(params4).then(function (res) {
    //     console.log('123456APPSetDeviceProperty', res);
    // });

    //因本项目在onenet平台的基础上修改得来，雷同处需要自行修改；
    //ALiIoT 平台链接方式    
    var data1 = {
      "ctrlpin": onoffbuf
    };
    // RRPC 向指定设备发送请求消息，并同步返回响应
    const config1 = {
      Action: "RRpc",
      ProductKey: api.productKey,
      DeviceName: api.deviceName,
      timeout: 6666,
      requestBase64Byte: base64.encode(JSON.stringify(data1)),
    };
    aliSdk.request(config1, {
      method: "POST"
    },
    (res) => {
      console.log("success")
      console.log(res) //查看返回response数据
      if (res.data.Code) {
        console.log(res.data.ErrorMessage)
        wx.showToast({
          title: '设备连接失败',
          icon: 'none',
          duration: 1000,
          complete: () => {}
        })
        // that.setPropertyData(null)
        console.log("1111nihao ")
      } else {
        // console.log("2222nihao ",res);
        console.log("2222nihao ",JSON.parse(base64.decode(res.data.PayloadBase64Byte)));
        // that.setPropertyData(res.data.Data.List.PropertyStatusInfo)
      }
    },
    (res) => {
      console.log("fail")
      wx.showToast({
        title: '网络连接失败',
        icon: 'none',
        duration: 1000,
        complete: () => {}
      })
      // this.setPropertyData(null)
    },
    (res) => {
      console.log("complete")
      
    })
  },
//led1灯开关  控制
onoff2(e) {
  // console.log('success!!',e);

  let onoffbuf = "";
  if(e.detail.value == true){
    onoffbuf = "0021";
  }else{
    onoffbuf = "0020";
  }
  const params4 = {
    query:{},
    "body": {
      "project_id": api.project_id,
      "product_id": api.product_id,
      "device_name": this.data.device_name,
      "params":{
        "ctrlpin": onoffbuf
      }
    }
  }
  onenetstudio.oneNetSDK.APPSetDeviceProperty(params4).then(function (res) {
      console.log('123456APPSetDeviceProperty', res);
  });
},
//led1灯开关  控制
onoff3(e) {
  // console.log('success!!',e);

  let onoffbuf = "";
  if(e.detail.value == true){
    onoffbuf = "0031";
  }else{
    onoffbuf = "0030";
  }
  const params4 = {
    query:{},
    "body": {
      "project_id": api.project_id,
      "product_id": api.product_id,
      "device_name": this.data.device_name,
      "params":{
        "ctrlpin": onoffbuf
      }
    }
  }
  onenetstudio.oneNetSDK.APPSetDeviceProperty(params4).then(function (res) {
      console.log('123456APPSetDeviceProperty', res);
  });
},
//继电器开/关  控制
relayctrl(e) {

  let ctrlbuf = "";
  if(e.detail.value == true){
    ctrlbuf = "0041";
  }else{
    ctrlbuf = "0040";
  }
  const params5 = {
    query:{},
    "body": {
      "project_id": api.project_id,
      "product_id": api.product_id,
      "device_name": this.data.device_name,
      "params":{
        "ctrlpin": ctrlbuf
      }
    }
  }
  onenetstudio.oneNetSDK.APPSetDeviceProperty(params5).then(function (res) {

      console.log('ctrlpin', res);

  });

},
//刷新设备状态  控制
refresh(e) {
  var that = this;
  const params3 = {
    query:{},
    "body": {
      "project_id": api.project_id,
      "product_id": api.product_id,
      "device_name": this.data.device_name,
      "params":{
        "useron": "01"
      }
    }
  }
  onenetstudio.oneNetSDK.APPSetDeviceProperty(params3).then(function (res) {
    // that.delay_refrash(that);
    console.log('useron', res);
    if(res.success == true){
      console.log('delay 1.2秒');
      setTimeout(function() {
        that.delay_refrash(that);
      }, 1300);
    }
    
  });
  
 
},
//延时刷新数据
delay_refrash:function (that) {
  const params11 = {
    query:{
        "project_id": api.project_id,
        "product_id": api.product_id,
        "device_name": this.data.device_name,
    },
    "body": {
        "params": {}
    }
  }
  onenetstudio.oneNetSDK.APPQueryDeviceProperty(params11).then(function (res) {

      console.log('APPQueryDeviceProperty', res);
      if(res.success == true){
        var propertydata = {};
        for (var propertyItem of res.data.list) {
          // console.log('APPQueryDeviceProperty', propertyItem);
          
          if (propertyItem.identifier == "RSSI") {
            propertydata.RSSI = propertyItem.value;
            var timestamp = Date.parse(new Date())/1000;
            propertydata.updata_min = parseInt((timestamp-parseInt(propertyItem.time/1000))/60);
            console.log('propertydata.updata_min111', propertydata.updata_min);
            propertydata.updata_sec = parseInt((timestamp-parseInt(propertyItem.time/1000))%60);
            console.log('propertydata.updata_min222S', propertydata.updata_sec);

          }
          if (propertyItem.identifier == "gear") {
            propertydata.read_gear = propertyItem.value;
          }
          if (propertyItem.identifier == "lingmin") {
            propertydata.lingmin = propertyItem.value;
          }
          if (propertyItem.identifier == "testa") {
            propertydata.testa = propertyItem.value;
          }
          if (propertyItem.identifier == "testb") {
            propertydata.testb = propertyItem.value;
          }
          if (propertyItem.identifier == "iostate") {
            propertydata.led_onoff1 = parseInt(propertyItem.value[7]);
            propertydata.led_onoff2 = parseInt(propertyItem.value[5]);
            propertydata.led_onoff3 = parseInt(propertyItem.value[4]);
          }
          if (propertyItem.identifier == "iostate") {
            propertydata.relay_ctrl1 = parseInt(propertyItem.value[6]);
          }
          if (propertyItem.identifier == "lng") {
            propertydata.lng = propertyItem.value;
          }
          if (propertyItem.identifier == "lat") {
            propertydata.lat = propertyItem.value;
          }
          if (propertyItem.identifier == "power") {
            propertydata.power = (propertyItem.value/1000);
          }
          if (propertyItem.identifier == "iostate") {
            propertydata.iostate = propertyItem.value;
          }
          if (propertyItem.identifier == "temp") {
            propertydata.dvc_temperature = propertyItem.value;
          }
          if (propertyItem.identifier == "adc") {
            propertydata.tgt_temperature = (propertyItem.value/100);
            propertydata.tgt_temperature = util.gettemp(propertyItem.value);
            // let test21 =util.gettemp(propertyItem.value);
            // console.log('dengwo chenggong!!!!', test21);
          }
          if (propertyItem.identifier == "comdata") {
            propertydata.comdata = propertyItem.value;
          }
        }
        console.log('propertydata2222', propertydata);
        that.setData(propertydata );

      }
      if((res.success == false)&&(res.msg == "device not online:device not online")){
        console.log(res.msg);
      }
      if((res.success == false)&&(res.msg == "device does not exist")){
        console.log(res.msg);
      }
      if((res.success == false)&&(res.msg == "timeout:acc timeout")){
        console.log(res.msg);
      }
      

  });
},
//刷新设备状态  控制
lingminctrl(e) {

  let ctrlbuf = "0" + e.detail.value.toString();
  console.log('666success!!',ctrlbuf);

  const params6 = {
    query:{},
    "body": {
      "project_id": api.project_id,
      "product_id": api.product_id,
      "device_name": this.data.device_name,
      "params":{
        "lingmin": ctrlbuf
      }
    }
  }
  onenetstudio.oneNetSDK.APPSetDeviceProperty(params6).then(function (res) {

      console.log('lingmin', res);

  });
  
  

},
//升档  控制
upctrl(e) {

  const params7 = {
    query:{},
    "body": {
      "project_id": api.project_id,
      "product_id": api.product_id,
      "device_name": this.data.device_name,
      "params":{
        "gear": 2
      }
    }
  }
  onenetstudio.oneNetSDK.APPSetDeviceProperty(params7).then(function (res) {

      console.log('gear', res);

  });

},
//降档  控制
downctrl(e) {

  const params8 = {
    query:{},
    "body": {
      "project_id": api.project_id,
      "product_id": api.product_id,
      "device_name": this.data.device_name,
      "params":{
        "gear": 3
      }
    }
  }
  onenetstudio.oneNetSDK.APPSetDeviceProperty(params8).then(function (res) {

      console.log('gear', res);

  });


},
//左转  控制
leftctrl(e) {

  const params9 = {
    query:{},
    "body": {
      "project_id": api.project_id,
      "product_id": api.product_id,
      "device_name": this.data.device_name,
      "params":{
        "rdevstate": 2
      }
    }
  }
  onenetstudio.oneNetSDK.APPSetDeviceProperty(params9).then(function (res) {

      console.log('rdevstate', res);

  });


},
//右转  控制
rightctrl(e) {

  const params9 = {
    query:{},
    "body": {
      "project_id": api.project_id,
      "product_id": api.product_id,
      "device_name": this.data.device_name,
      "params":{
        "rdevstate": 3
      }
    }
  }
  onenetstudio.oneNetSDK.APPSetDeviceProperty(params9).then(function (res) {

      console.log('rdevstate', res);

  });

},
lixianpop() {
  if (this.data.annualfeeendtime==0){
    wx.showToast({
      title: '数据服务已到期，请点击数据服务续费',
      icon: 'none',
    })
  }else{
    wx.showToast({
      title: '当前设备处于离线状态',
      icon: 'none',
    })
  }
},

})
